package com.github.postsanf.yinian.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import com.github.postsanf.yinian.BaseActivity;
import com.github.postsanf.yinian.R;
import com.github.postsanf.yinian.bean.Tag;
import com.github.postsanf.yinian.bean.YNTag;
import com.github.postsanf.yinian.constants.CommonConstants;
import com.github.postsanf.yinian.entity.YNTagResponse;
import com.github.postsanf.yinian.utils.ReqUtils;
import com.github.postsanf.yinian.widget.TagCloudLinkView;
import com.litesuits.http.exception.HttpException;
import com.litesuits.http.listener.HttpListener;
import com.litesuits.http.request.StringRequest;
import com.litesuits.http.request.param.HttpMethods;
import com.litesuits.http.response.Response;
import com.umeng.analytics.MobclickAgent;

import java.util.LinkedHashMap;
import java.util.List;

public class MemoryCardLabel extends BaseActivity implements OnClickListener {
    private TagCloudLinkView hot_tag;
    private TagCloudLinkView all_tag;
    private TagCloudLinkView history_tag;
    private InputMethodManager inputMethodManager;
    private EditText labET;
    private ImageButton labClear;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.act_pubone_label);
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
        inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        findViewById(R.id.pubone_label_back).setOnClickListener(this);
        findViewById(R.id.pubone_label_sure).setOnClickListener(this);
        findViewById(R.id.pubone_label_add).setOnClickListener(this);
        all_tag = (TagCloudLinkView) findViewById(R.id.all_tag);
        hot_tag = (TagCloudLinkView) findViewById(R.id.hot_tag);
        history_tag = (TagCloudLinkView) findViewById(R.id.history_tag);
        if (MemoryCardEditActivity.tagList.size() > 0) {
            for (int j = 0; j < MemoryCardEditActivity.tagList.size(); j++) {
                all_tag.add(new Tag(j, MemoryCardEditActivity.tagList.get(j).getText()));
            }
            all_tag.drawTags(R.drawable.mycard_guide_tag_green, R.color.white, 12);
        }
        hot_tag.setOnTagSelectListener(new TagCloudLinkView.OnTagSelectListener() {
            @Override
            public void onTagSelected(Tag tag, int i, View tagView, TextView textView) {
                if (checkTagISExist(tag.getText())) {
                    showToast("标签已选择");
                    return;
                }
                tagView.setBackgroundResource(R.drawable.mycard_guide_tag_green);
                textView.setTextColor(getResources().getColor(R.color.white));
                all_tag.add(new Tag(1, tag.getText()));
                all_tag.drawTags(R.drawable.mycard_guide_tag_green, R.color.white, 12);
            }
        });
        history_tag.setOnTagSelectListener(new TagCloudLinkView.OnTagSelectListener() {
            @Override
            public void onTagSelected(Tag tag, int i, View tagView, TextView textView) {
                if (checkTagISExist(tag.getText())) {
                    showToast("标签已选择");
                    return;
                }
                tagView.setBackgroundResource(R.drawable.mycard_guide_tag_green);
                textView.setTextColor(getResources().getColor(R.color.white));
                all_tag.add(new Tag(2, tag.getText()));
                all_tag.drawTags(R.drawable.mycard_guide_tag_green, R.color.white, 12);
            }
        });
        all_tag.setOnTagDeleteListener(new TagCloudLinkView.OnTagDeleteListener() {
            @Override
            public void onTagDeleted(Tag tag, int position) {
                String tt = tag.getText();
                for (int i = 0; i < hot_tag.getTags().size(); i++) {
                    if (tt.equals(hot_tag.getTags().get(i).getText())) {
                        View tagView = hot_tag.getViews().get(i);
                        tagView.setBackgroundResource(R.drawable.mycard_guide_tag_gray);
                        TextView textView = (TextView) tagView.findViewById(R.id.tag_txt);
                        textView.setTextColor(getResources().getColor(R.color.user_color_green));
                    }
                }
                for (int i = 0; i < history_tag.getTags().size(); i++) {
                    if (tt.equals(history_tag.getTags().get(i).getText())) {
                        View tagView = history_tag.getViews().get(i);
                        tagView.setBackgroundResource(R.drawable.mycard_guide_tag_gray);
                        TextView textView = (TextView) tagView.findViewById(R.id.tag_txt);
                        textView.setTextColor(getResources().getColor(R.color.user_color_green));
                    }
                }
                for (int i = 0; i < MemoryCardEditActivity.tagList.size(); i++) {
                    if (tt.equals(MemoryCardEditActivity.tagList.get(i).getText())) {
                        MemoryCardEditActivity.tagList.remove(i);
                    }
                }
            }
        });
        labET = (EditText) findViewById(R.id.publabel_edit);
        labClear = (ImageButton) findViewById(R.id.publabel_clear);
        labClear.setOnClickListener(this);
        labET.addTextChangedListener(new TextWatcher() {
            public void onTextChanged(CharSequence s, int start, int before,
                                      int count) {
                if (s.length() > 0) {
                    labClear.setVisibility(View.VISIBLE);
                } else {
                    labClear.setVisibility(View.INVISIBLE);
                }
            }

            public void beforeTextChanged(CharSequence s, int start, int count,
                                          int after) {
            }

            public void afterTextChanged(Editable s) {
            }
        });
        updateHotHistoryList();
    }

    private boolean checkTagISExist(String tagtt) {
        boolean bb = false;
        for (int j = 0; j < all_tag.getTags().size(); j++) {
            if (tagtt.equals(all_tag.getTags().get(j).getText())) {
                bb = true;
            }
        }
        return bb;
    }

    private void hidesoftkeyword() {
        inputMethodManager.hideSoftInputFromWindow(MemoryCardLabel.this
                .getCurrentFocus().getWindowToken(), 0);
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.pubone_label_back:
                hidesoftkeyword();
                finish();
                break;
            case R.id.publabel_clear:
                labET.getText().clear();
                break;
            case R.id.pubone_label_add:
                String tagcontent = labET.getText().toString();
                if (tagcontent == null || tagcontent.equals("")) {
                    Toast.makeText(MemoryCardLabel.this, "标签不能为空", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (tagcontent.length() > 12) {
                    Toast.makeText(MemoryCardLabel.this, "标签内容过长", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (checkTagISExist(tagcontent)) {
                    showToast("标签已选择");
                    labET.getText().clear();
                    return;
                }
                all_tag.add(new Tag(1, tagcontent));
                all_tag.drawTags(R.drawable.mycard_guide_tag_green, R.color.white, 12);
                labET.getText().clear();
                hidesoftkeyword();
                break;
            case R.id.pubone_label_sure:
                if (all_tag.getTags().size() > 0) {
                    MemoryCardEditActivity.tagList.clear();
                    for (int i = 0; i < MemoryCardEditActivity.tagList.size(); i++) {
                        MemoryCardEditActivity.tagList.remove(i);
                    }
                    for (int i = 0; i < all_tag.getTags().size(); i++) {
                        MemoryCardEditActivity.tagList.add(all_tag.getTags().get(i));
                    }
                    Intent intent = getIntent();
                    intent.putExtra("tags", "tags");
                    setResult(MemoryCardEditActivity.TAKE_TAG, intent);// 返回参数
                    hidesoftkeyword();
                    finish();
                } else {
                    showToast("未选择标签");
                }
                break;
            default:
                break;
        }
    }

    private void updateHotHistoryList() {
        LinkedHashMap<String, String> mParam = new LinkedHashMap<>();
        mParam.put(CommonConstants.YNS_USER_ID, String.valueOf(application.getCurID()));
        StringRequest req = new StringRequest(getString(R.string.BASE_URL) + getString(R.string.GetUserAllTags))
                .setMethod(HttpMethods.Post)
                .setParamMap(mParam)
                .setHttpListener(new HttpListener<String>(true, false, true) {
                    @Override
                    public void onSuccess(String s, Response<String> response) {
                        YNTagResponse resAlertBg = gson.fromJson(s, YNTagResponse.class);
                        if (ReqUtils.isSuccess(resAlertBg.getCode())) {
                            List<YNTag> YNTaglist = resAlertBg.getData();
                            for (int i = 0; i < YNTaglist.size(); i++) {
                                YNTag ynTag = YNTaglist.get(i);
                                if (ynTag.getTagType() == 2) {
                                    hot_tag.add(new Tag(2, ynTag.getTagContent()));
                                } else if (ynTag.getTagType() == 1) {
                                    history_tag.add(new Tag(1, ynTag.getTagContent()));
                                }
                            }
                            hot_tag.drawTags(R.drawable.mycard_guide_tag_gray, R.color.user_color_green, 12);
                            history_tag.drawTags(R.drawable.mycard_guide_tag_gray, R.color.user_color_green, 12);
                        }
                    }

                    @Override
                    public void onFailure(HttpException e, Response<String> response) {
                        showToast(CommonConstants.YN_NET_LINK);
                    }
                });
        liteHttp.executeAsync(req);
    }

    // 友盟统计
    public void onResume() {
        super.onResume();
        MobclickAgent.onPageStart(this.getClass().getSimpleName());
        MobclickAgent.onResume(this);
    }

    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd(this.getClass().getSimpleName());
        MobclickAgent.onPause(this);
    }
}
